package com.lottery.material.util;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Description：导出Excel的工具类
 * Created by 朱正磊 on 2019-06-05 14:49
 */
@SuppressWarnings("ALL")
public class ExportExcelUtil {

    /**
     * description：设置响应头
     * user 朱正磊
     * time 2019-06-05 13:44
     * @param response 响应对象
     * @param fileName 文件名称
     */
    public static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".zip");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * description：将文件进行zip压缩
     * user 朱正磊
     * time 2019-06-05 13:45
     * @param srcfile 文件名数组
     * @param zipfile 压缩后文件
     */
    public static void zipFiles(File[] srcfile, File zipfile) {
        byte[] buf = new byte[1024];
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
            for (int i = 0; i < srcfile.length; i++) {
                FileInputStream in = new FileInputStream(srcfile[i]);
                out.putNextEntry(new ZipEntry(srcfile[i].getName()));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * description：删除文件
     * user 朱正磊
     * time 2019-06-05 13:46
     * @param fileNames 文件名集合
     * @param zipPath 压缩文件路径
     */
    public static void deleteFile(List<String> fileNames, String zipPath) {
        String sPath;
        File file;
        try {
            // 判断目录或文件是否存在
            for (int i = 0; i < fileNames.size(); i++) {
                sPath = fileNames.get(i);
                file = new File(sPath);
                if (file.exists()) {
                    file.delete();
                }
            }
            file = new File(zipPath);
            if (file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
